// pages/buy/buy.js
const app = getApp();
Page({
  data: {
    vipPlans: [
      {
        name: '月度VIP',
        price: 0,
        oldPrice: 0
      },
      {
        name: '季度VIP',
        price: 0,
        oldPrice: 0
      },
      {
        name: '年度VIP',
        price: 0,
        oldPrice: 0
      }
    ],
    selectedPlanIndex: 0
  },
  onLoad() {
    let category = app.globalData.category;
    let vip = category.vip;
    let vipPlans = this.data.vipPlans;
    vipPlans[0].price = vip.m.price;
    vipPlans[0].oldPrice = vip.m.original_price;
    vipPlans[0].type = 'm';

    vipPlans[1].price = vip.q.price;
    vipPlans[1].oldPrice = vip.q.original_price;
    vipPlans[1].type = 'q';

    vipPlans[2].price = vip.y.price;
    vipPlans[2].oldPrice = vip.y.original_price;
    vipPlans[2].type = 'y';
    console.log(vipPlans);
    this.setData({
      vipPlans: vipPlans
    });
    this.category_id = category.id;
  },

  selectPlan(e) {
    this.setData({
      selectedPlanIndex: e.currentTarget.dataset.index
    });
  },

  buyNow() {
    wx.showLoading();
    const selectedPlan = this.data.vipPlans[this.data.selectedPlanIndex];
    console.log('selectedPlan', selectedPlan);
    // 调起微信支付
    const that = this;
    app.request('/api/user/addOrder', {question_category_id: this.category_id, type: selectedPlan.type}, 'POST').then(res => {
      wx.cloud.callFunction({
        name: 'payment',
        data: {
          body: selectedPlan.name,
          outTradeNo: res.data.data.id.toString(),
          totalFee: parseInt(res.data.data.money * 100)
        },
        success: res => {
          const payment = res.result.payment
          wx.requestPayment({
            ...payment,
            success (res) {
              console.log('pay success', res);
              wx.showLoading({
                title: '正在解锁题目',
              });
              setTimeout(() => {
                app.request('/api/user/info', {question_category_id: that.category_id}).then(res => {
                  app.globalData.userinfo = res.data.data;
                  wx.hideLoading();
                  wx.navigateBack();
                }).catch(err => {
                  wx.hideLoading();
                  wx.navigateBack();
                  console.error(err);
                });
              }, 2000);
            },
            fail (err) {
              wx.hideLoading();
              wx.showToast({
                title: '取消支付',
                icon: 'none'
              })
              console.log('取消支付', err);
            }
          })
          console.log(res);
        },
        fail: (err) => {
          console.error('payment云函数调用失败', err);
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    }).catch(err => {
      console.error(err);
    })
    
  }
});
